<template>
  <!-- 
	 1.具备输入框的样式
	 2.不可输入
	 3.placeholder内容可以在父组件定义
	 -->
  <view class="my-search-caontainer">
    <!-- 搜索输入框 -->
    <uni-search-bar
      v-if="isShowInput"
      class="my-search-bar"
      :radius="100"
      :bgColor="config.backgroundColor"
      :placeholder="placeholderText"
      :value="value"
      @confirm="onSearch"
      @focus="onFocus"
      @blur="onBlur"
      @clear="onClear"
      @cancel="onCancel"
      @input="onInput"
    >
      <uni-icons slot="clearIcon" type="clear" color="#999999" />
    </uni-search-bar>
    <!-- 搜索按钮 -->
    <view
      class="my-search-box"
      v-else
      :style="{
        height: config.height + 'px',
        backgroundColor: config.backgroundColor,
        border: config.border,
      }"
    >
      <!-- 搜索图标 -->
      <image class="icon" :src="config.icon"></image>
      <text class="placeholder" :style="{ color: config.textColor }">{{
        placeholderText
      }}</text>
    </view>
  </view>
</template>

<script>
export default {
  name: "my-search",
  props: {
    //search-bar不可以使用v-model，因为直接使用v-model会修改父组件传递的数据
    value: {
      type: String,
    },
    placeholderText: {
      type: String,
      default: "搜索",
    },
    //是否显示输入框
    isShowInput: {
      type: Boolean,
      default: false,
    },
    //配置对象
    config: {
      type: Object,
      default: () => ({
        height: 36,
        backgroundColor: "#ffff",
        icon: "/static/images/search.png",
        textColor: "#454545",
        border: "1px solid #c9c9c9",
      }),
    },
  },
  data() {
    return {};
  },
  methods: {
    // 点击搜索按钮触发
    onSearch() {
      this.$emit("search", this.value);
    },
    //获得焦点触发
    onFocus() {
      this.$emit("focus", this.value);
    },
    //失去焦点触发
    onBlur() {
      this.$emit("blur", this.value);
    },
    //点击输入框中清空按钮
    onClear() {
      this.$emit("clear", this.value);
    },
    //点击取消按钮
    onCancel() {
      this.$emit("cancel", this.value);
    },
    //输入框的value改变时触发
    onInput(val) {
      //通知父组件
      this.$emit("input", val);
    },
  },
};
</script>

<style lang="scss" scoped>
.my-search-caontainer {
  display: flex;
  align-items: center;
  .my-search-bar {
    width: 100%;
  }
  .my-search-box {
    width: 100%;
    height: 36px;
    background-color: $uni-bg-color;
    border-radius: 15px;
    border: 1px solid $uni-bg-color-border;
    display: flex;
    align-items: center;
    padding: 0 $uni-spacing-row-base;
    .icon {
      width: $uni-img-size-sm;
      height: $uni-img-size-sm;
    }
    .placeholder {
      font-size: $uni-font-size-sm;
      margin-left: $uni-font-size-sm;
      color: $uni-text-color-placeholder;
    }
  }
}
</style>
